<?php

function getStubPath($name)
{
    return app()->getRootPath() . "addons" . DIRECTORY_SEPARATOR . "gs_developer" . DIRECTORY_SEPARATOR . "utils" . DIRECTORY_SEPARATOR . "stubs" . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $name) . '.stub';
}


/**
 * 组装模板
 * @param string $name
 * @param array $data
 * @return string
 */
function assembleStub($name, $data)
{
    foreach ($data as &$datum) {
        $datum = is_array($datum) ? implode(PHP_EOL, $datum) : $datum;
    }
    $search = $replace = [];
    foreach ($data as $k => $v) {
        $search[] = "{%$k%}";
        $replace[] = $v;
    }
    $stubPath = getStubPath($name);
    $stubContent = file_get_contents($stubPath);
    $content = str_replace($search, $replace, $stubContent);
    return $content;
//    return $escape ? self::escape($content) : $content;
}


/** 递归打包文件夹（修复跨平台路径问题）
 * @param $source
 * @param $destination
 * @return bool
 */
function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }
    $zip = new ZipArchive();
    if (!$zip->open($destination, ZipArchive::CREATE)) {
        return false;
    }
    // 统一路径分隔符并获取真实路径
    $source = realpath($source);
    if ($source === false) {
        $zip->close();
        return false;
    }
    // 统一使用正斜杠
    $source = str_replace('\\', '/', $source);
    $sourceLen = strlen($source);
    if (is_dir($source)) {
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($source),
            RecursiveIteratorIterator::SELF_FIRST
        );
        foreach ($files as $file) {
            $filePath = $file->getRealPath();
            // 跳过无效路径
            if ($filePath === false) {
                continue;
            }
            // 统一路径分隔符
            $filePath = str_replace('\\', '/', $filePath);
            // 跳过 . 和 .. 目录
            if ($file->isDir()) {
                $dirname = $file->getFilename();
                if ($dirname === '.' || $dirname === '..') {
                    continue;
                }
            }
            // 计算相对路径
            $relativePath = '';
            if (strlen($filePath) > $sourceLen) {
                $relativePath = substr($filePath, $sourceLen + 1);
            }
            // 如果相对路径为空，跳过（通常是源目录本身）
            if (empty($relativePath)) {
                continue;
            }
            if ($file->isDir()) {
                // 添加目录（确保以 / 结尾）
                $zip->addEmptyDir($relativePath . '/');
            } elseif ($file->isFile()) {
                // 添加文件
                $zip->addFile($filePath, $relativePath);
            }
        }
    } elseif (is_file($source)) {
        // 单个文件
        $zip->addFile($source, basename($source));
    }

    return $zip->close();
}
